package com.sptpc.demo1.service.impl;

import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.repository.CategoryRepository;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.service.IDrinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;
import java.util.Optional;

@Service
public class DrinkJpaService implements IDrinkService {
    @Autowired
    private DrinkRepository drinkRepository;

    @Autowired
    private CategoryRepository categoryRepositor;

    @Override
    public List<Drink> getAllDrinks(){
        return drinkRepository.findAll();
    }

    @Override
    public void addNewDrink(Drink drink,Integer categoryId) {
        //通过categoryId查询category
        Category category=categoryRepositor.findById(categoryId).orElse(null);
        //将category设置给drink
        drink.setCategory(category);
        drinkRepository.save(drink);
    }

    @Override
    public Drink getDrinkById(Integer id) {
//        Optional<Drink> optional=drinkRepository.findAllById(id);
//        if (optional.isPresent()){
//            return optional.get();
//        }
//        return null;
        return drinkRepository.findById(id).orElse(null);
    }

    @Override
    public void updateDrink(Drink drink) {
        drinkRepository.save(drink);
    }

    @Override
    public void deleteDrinkId(Integer id) {
        drinkRepository.deleteById(id);
    }


}

